package com.spark.concurrency.thread;

import org.apache.tomcat.util.threads.TaskThread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 4, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                System.out.println("线程" + r.hashCode() + "被创建");
                Thread thread = new Thread(r, "name" + r.hashCode());
                return thread;
            }
        }, new ThreadPoolExecutor.CallerRunsPolicy()) {//相当于创建了一个类，重写ThreadPoolExecutor里面的方法
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("准备执行" + ((ThreadTask) r).getTaskName());
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("执行完成" + ((ThreadTask) r).getTaskName());
            }

            @Override
            protected void terminated() {
                System.out.println("线程池推出");
            }
        };
        for (int i = 0; i < 10; i++) {
            pool.execute(new ThreadTask("Task" + i));
        }
        pool.shutdown();
    }

    static class ThreadTask implements Runnable {
        private String taskName;

        public String getTaskName() {
            return taskName;
        }

        public ThreadTask(String taskName) {
            this.taskName = taskName;
        }

        @Override
        public void run() {
            System.out.println("TaskName:" + taskName + "------ThreadName:" + Thread.currentThread().getName());
        }
    }
}
